package com.action.gulimall.seckill.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sl shilun217@qq.com
 * @Deacription 公用线程池
 * @date 2021/06/24/0:40
 **/
@EnableConfigurationProperties(value = {MyThreadPoolConfig.MyThreadPoolProperties.class})
@Configuration
public class MyThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor globalExecutor(MyThreadPoolProperties myThreadPoolProperties){
        return new ThreadPoolExecutor(myThreadPoolProperties.getCorePoolSize(),
                myThreadPoolProperties.getMixmumPoolSize(),
                myThreadPoolProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(myThreadPoolProperties.getQueueSize()),
                new DefaultThreadFactory("global"),
                new ThreadPoolExecutor.AbortPolicy());
    }

    @Data
    @ConfigurationProperties(prefix = "my.thread.pool")
    public static class MyThreadPoolProperties{

        private Integer corePoolSize=5;

        private Integer mixmumPoolSize=10;

        private Long keepAliveTime=30L;

        private Integer queueSize=1000;
    }

    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory(String namePrefix) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            this.namePrefix =namePrefix+ "-pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
